package com.pig4cloud.pig.ads.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.api.client.util.Lists;
import com.pig4cloud.pig.ads.service.AdLandingPageService;
import com.pig4cloud.pig.ads.service.AdvService;
import com.pig4cloud.pig.ads.utils.DateUtils;
import com.pig4cloud.pig.api.entity.AdLandingPage;
import com.pig4cloud.pig.api.entity.LandingGroup;
import com.pig4cloud.pig.api.gdt.vo.LandingGroupVo;
import com.pig4cloud.pig.api.vo.Site;
import com.pig4cloud.pig.common.core.constant.enums.PlatformTypeEnum;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.annotation.Inner;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author yk
 * @ 程序化落地页 前端控制器
 */
@Log4j2
@RestController
@RequiredArgsConstructor
@RequestMapping("/landingGroup")
@Api(value = "LandingGroup", tags = "程序化落地页管理模块")
public class LandingGroupController {

	private final AdvService advService;

	private final AdLandingPageService adLandingPageService;

	/**
	 * 分页查询落地页信息
	 *
	 * @return 分页对象
	 */
	@RequestMapping("/getPage")
	public R getPage(LandingGroupVo req, Page<LandingGroup> page) {
		//获取到当前登录用户
		Integer id = SecurityUtils.getUser().getId();
		//通过登录用户去查询多个广告主id
		List<String> allList = advService.getOwnerAdv(id, PlatformTypeEnum.TT.getValue());
		if (allList == null || allList.isEmpty()) {
			return R.ok(page);
		}
		//设置where条件
		QueryWrapper<AdLandingPage> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("platform_id", PlatformTypeEnum.TT.getValue());
		queryWrapper.eq("page_type", "TT_GROUP");
		//根据广告主id查询
		String[] advArr = req.getAdvertiserIds();
		if (advArr == null || advArr.length == 0) {
			//查询所有
			queryWrapper.in("advertiser_id", allList);
		} else {
			List<String> selectList = Arrays.asList(advArr);
			if (!allList.containsAll(selectList)) {
				return R.failed("广告账户不可用");
			}
			queryWrapper.in("advertiser_id", selectList);
		}
		//根据落地页名称模糊查询
		if (StringUtils.isNotBlank(req.getGroupTitle())) {
			queryWrapper.like("page_name", req.getGroupTitle());
		}
		//根据落地页id精确查询
		if (StringUtils.isNotBlank(req.getGroupId())) {
			queryWrapper.eq("page_id", req.getGroupId());
		}
		queryWrapper.orderByAsc("advertiser_id");
		queryWrapper.orderByDesc("order_number");
		// 分页查询
		IPage<AdLandingPage> iPage = adLandingPageService.getLandingIPage(page, queryWrapper);

		// 重新组装返回对象
		IPage<LandingGroup> resultPage = new Page<>();
		BeanUtils.copyProperties(iPage, resultPage);
		List<LandingGroup> resultList = Lists.newArrayList();
		if (Objects.nonNull(iPage) && CollectionUtils.isNotEmpty(iPage.getRecords())) {
			for (AdLandingPage adLandingPage : iPage.getRecords()) {
				resultList.add(dealData(adLandingPage));
			}
		}
		resultPage.setRecords(resultList);
		return R.ok(resultPage, "操作成功");
	}

	@RequestMapping("/preview")
	public R preview(String groupId) {
		if (StringUtils.isBlank(groupId)) {
			return R.failed("未将程序化落地页id传给后台");
		}
		QueryWrapper<AdLandingPage> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("platform_id", PlatformTypeEnum.TT.getValue());
		queryWrapper.eq("page_type", "TT_GROUP");
		queryWrapper.eq("page_id", groupId);
		queryWrapper.last("LIMIT 1");
		AdLandingPage adLandingPage = adLandingPageService.getOne(queryWrapper);
		if (Objects.isNull(adLandingPage)) {
			return R.failed("无此程序化落地页");
		}
		LandingGroup landingGroup = dealData(adLandingPage);

		List<Site> selectList = Lists.newArrayList();
		if (StringUtils.isNotBlank(landingGroup.getSites())) {
			List<Site> list = JSON.parseArray(landingGroup.getSites(), Site.class);
			List<String> siteIds = list.stream().map(Site::getSite_id).collect(Collectors.toList());

			QueryWrapper<AdLandingPage> wrapperAdLanding = new QueryWrapper<>();
			wrapperAdLanding.eq("platform_id", PlatformTypeEnum.TT.getValue());
			wrapperAdLanding.eq("page_type", "TT_ORANGE");
			wrapperAdLanding.in("page_id", siteIds);
			List<AdLandingPage> adLandingPageList = adLandingPageService.list(wrapperAdLanding);
			for (Site site : list) {
				site.setGroupId(groupId);
				if ("ACCEPTED".equals(site.getSite_audit_status())) {
					String siteId = site.getSite_id();
					for (AdLandingPage adLanding : adLandingPageList) {
						if (adLanding.getPageId().equals(siteId)) {
							site.setSiteName(adLanding.getPageName());
							selectList.add(site);
						}
					}
				}
			}
		}
		return R.ok(selectList, "操作成功");
	}


	@RequestMapping("/getSites")
	public R getPage(String groupId) {
		if (StringUtils.isBlank(groupId)) {
			return R.failed("未将程序化落地页id传给后台");
		}
		QueryWrapper<AdLandingPage> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("platform_id", PlatformTypeEnum.TT.getValue());
		queryWrapper.eq("page_type", "TT_GROUP");
		queryWrapper.eq("page_id", groupId);
		queryWrapper.last("LIMIT 1");
		AdLandingPage adLandingPage = adLandingPageService.getOne(queryWrapper);
		if (Objects.isNull(adLandingPage)) {
			return R.failed("无此程序化落地页");
		}
		LandingGroup landingGroup = dealData(adLandingPage);

		if (StringUtils.isNotBlank(landingGroup.getSites())) {
			List<Site> list = JSON.parseArray(landingGroup.getSites(), Site.class);
			List<String> siteIds = list.stream().map(Site::getSite_id).collect(Collectors.toList());

			QueryWrapper<AdLandingPage> wrapperAdLanding = new QueryWrapper<>();
			wrapperAdLanding.eq("platform_id", PlatformTypeEnum.TT.getValue());
			wrapperAdLanding.eq("page_type", "TT_ORANGE");
			wrapperAdLanding.in("page_id", siteIds);
			List<AdLandingPage> adLandingPageList = adLandingPageService.list(wrapperAdLanding);
			for (Site site : list) {
				site.setGroupId(groupId);
				for (AdLandingPage adLanding : adLandingPageList) {
					if (adLanding.getPageId().equals(site.getSite_id())) {
						site.setSiteName(adLanding.getPageName());
						site.setSite_audit_status(adLanding.getStatus());
					}
				}
			}
			return R.ok(list, "操作成功");
		}
		return R.ok(Lists.newArrayList(), "操作成功");
	}

	@RequestMapping("/getUrl")
	public R previewById(String groupId, String memberId) {
		if (StringUtils.isBlank(groupId)) {
			return R.failed("未将程序化落地页id传给后台");
		}
		if (StringUtils.isBlank(memberId)) {
			return R.failed("未将子落地页成员id传给后台");
		}
		QueryWrapper<AdLandingPage> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("platform_id", PlatformTypeEnum.TT.getValue());
		queryWrapper.eq("page_type", "TT_GROUP");
		queryWrapper.eq("page_id", groupId);
		queryWrapper.last("LIMIT 1");
		AdLandingPage adLandingPage = adLandingPageService.getOne(queryWrapper);
		if (Objects.isNull(adLandingPage)) {
			return R.failed("无此程序化落地页");
		}
		LandingGroup landingGroup = dealData(adLandingPage);

		List<Site> list = JSON.parseArray(landingGroup.getSites(), Site.class);
		for (Site site : list) {
			if (memberId.equals(site.getMember_id())) {
				return R.ok(site.getSite_url(), "操作成功");
			}
		}
		return R.failed("子落地页成员ID输入错误");
	}

	@RequestMapping("/getSelectPage")
	public R getSelectPage(LandingGroupVo req, Page<LandingGroup> page) {
		//获取到当前登录用户
		Integer id = SecurityUtils.getUser().getId();
		//通过登录用户去查询多个广告主id
		List<String> allList = advService.getOwnerAdv(id, PlatformTypeEnum.TT.getValue());
		if (allList == null || allList.isEmpty()) {
			return R.ok(page);
		}
		//设置where条件
		QueryWrapper<AdLandingPage> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("platform_id", PlatformTypeEnum.TT.getValue());
		queryWrapper.eq("page_type", "TT_GROUP");
		//根据广告主id查询
		String adv = req.getAdvertiserId();
		if (StringUtils.isBlank(adv)) {
			return R.failed("未传入广告主id");
		}
		if (!allList.contains(adv)) {
			return R.failed("广告账户不可用");
		}
		queryWrapper.eq("advertiser_id", adv);
		queryWrapper.eq("status", "LANDING_GROUP_STATUS_AVAILABLE");
		//根据落地页名称模糊查询
		if (!StringUtils.isBlank(req.getGroupTitle())) {
			queryWrapper.like("page_name", req.getGroupTitle());
		}
		//根据落地页id查询
		if (!StringUtils.isBlank(req.getGroupId())) {
			queryWrapper.eq("page_id", req.getGroupId());
		}
		queryWrapper.orderByDesc("order_number");
		// 分页查询
		IPage<AdLandingPage> iPage = adLandingPageService.getLandingIPage(page, queryWrapper);

		// 重新组装返回对象
		IPage<LandingGroup> resultPage = new Page<>();
		BeanUtils.copyProperties(iPage, resultPage);
		List<LandingGroup> resultList = Lists.newArrayList();
		if (Objects.nonNull(iPage) && CollectionUtils.isNotEmpty(iPage.getRecords())) {
			for (AdLandingPage adLandingPage : iPage.getRecords()) {
				resultList.add(dealData(adLandingPage));
			}
		}
		resultPage.setRecords(resultList);
		return R.ok(resultPage, "操作成功");
	}

	/**
	 * 20220318 落地页改造统一表，前段不改动 ，后端数据重组
	 *
	 * @param adLandingPage
	 * @return
	 */
	private LandingGroup dealData(AdLandingPage adLandingPage) {
		if (Objects.nonNull(adLandingPage)) {
			LandingGroup landingGroup = new LandingGroup();
			landingGroup.setGroupId(adLandingPage.getPageId());
			landingGroup.setGroupTitle(adLandingPage.getPageName());
			landingGroup.setGroupUrl(adLandingPage.getPageUrl());
			landingGroup.setGroupStatus(adLandingPage.getStatus());
			landingGroup.setGroupFlowType(adLandingPage.getGroupFlowType());
			landingGroup.setSites(adLandingPage.getComps());
			landingGroup.setAdvertiserId(adLandingPage.getAdvertiserId());
			landingGroup.setCreateTime(DateUtils.dateToString(adLandingPage.getCreateTime(), DateUtils.YYYY_MM_DD_HH_MM_SS));
			landingGroup.setUpdateTime(DateUtils.dateToString(adLandingPage.getUpdateTime(), DateUtils.YYYY_MM_DD_HH_MM_SS));
			landingGroup.setOrderNumber(adLandingPage.getOrderNumber());
			if (StringUtils.isNotBlank(adLandingPage.getComps())) {
				List<Site> list = JSON.parseArray(adLandingPage.getComps(), Site.class);
				landingGroup.setNumber(list.size());
			}
			return landingGroup;
		}
		return null;
	}

	/**
	 * 根据素材ID列表查询素材信息
	 *
	 * @param landingPageIds
	 * @return
	 */
	@Inner
	@PostMapping("/getLandingPageListByIds")
	public R<List<AdLandingPage>> getLandingPageListByIds(@RequestBody List<String> landingPageIds) {
		List<AdLandingPage> landingPageListByIds = adLandingPageService.getLandingPageListByIds(landingPageIds);
		return R.ok(landingPageListByIds);
	}

}
